package mongo

import (
	"beego/models"
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var mgoCli *mongo.Client

func initDb() {
	var err error
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
	//连接mongodb

	mgoCli, err = mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	//检查连接
	err = mgoCli.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
}
func MgoCli() *mongo.Client {
	if mgoCli == nil {
		initDb()
	}
	return mgoCli
}
func MongoCountPoem() int {
	var (
		client     = MgoCli()
		collection *mongo.Collection
	)
	collection = client.Database("poem").Collection("poem")
	cond := models.FindAll{}
	count, _ := collection.CountDocuments(context.TODO(), cond)
	return int(count)
}

func GetPoem(id int) []models.Poem {
	var (
		client     = MgoCli()
		err        error
		collection *mongo.Collection
		cursor     *mongo.Cursor
	)
	collection = client.Database("poem").Collection("poem")
	cond := models.FindById{Id: id}
	if cursor, err = collection.Find(
		context.TODO(),
		cond,
		options.Find().SetSkip(0)); err != nil {
		fmt.Println(err)
	}
	defer func() {
		if err = cursor.Close(context.TODO()); err != nil {
			log.Fatal(err)
		}
	}()
	//遍历游标获取结果数据
	for cursor.Next(context.TODO()) {
		var lr models.Poem
		//反序列化Bson到对象
		if cursor.Decode(&lr) != nil {
			fmt.Print(err)
		}
	}
	var result []models.Poem
	if err = cursor.All(context.TODO(), &result); err != nil {
		log.Fatal(err)

	}

	return result
}

func SetManyPoems() {
	var (
		client     = MgoCli()
		err        error
		collection *mongo.Collection
		result     *mongo.InsertManyResult
		id         primitive.ObjectID
	)
	collection = client.Database("poem").Collection("poem")
	result, err = collection.InsertMany(context.TODO(), []interface{}{
		models.Poem{
			Id:         1,
			PoemName:   "己亥杂诗",
			AuthorName: "龚自珍",
			Dynasty:    "清",
			Content:    "落红不是无情物，化作春泥更护花"},
		models.Poem{
			Id:         2,
			PoemName:   "陋室铭",
			AuthorName: "刘禹锡",
			Dynasty:    "唐",
			Content:    "斯是陋室，惟吾德馨"},
		models.Poem{
			Id:         3,
			PoemName:   "三国演义",
			AuthorName: "吕布",
			Dynasty:    "东汉",
			Content:    "大丈夫生居于天地间，岂能郁郁久居人下"},
		models.Poem{
			PoemName:   "将进酒",
			AuthorName: "李白",
			Dynasty:    "唐",
			Content:    "天生我才必有用，千金散尽还复来",
			Id:         4,
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	if result == nil {
		log.Fatal("result nil")
	}
	for _, v := range result.InsertedIDs {
		id = v.(primitive.ObjectID)
		fmt.Println("自增ID", id.Hex())
	}

}

func GetWord(id int, class string) []models.Word {
	var (
		client     = MgoCli()
		err        error
		collection *mongo.Collection
		cursor     *mongo.Cursor
	)
	collection = client.Database("english").Collection("word")
	cond := models.FindByClassAndId{Id: id, Class: class}
	if cursor, err = collection.Find(
		context.TODO(),
		cond,
		options.Find().SetSkip(0)); err != nil {
		fmt.Println(err)
	}
	defer func() {
		if err = cursor.Close(context.TODO()); err != nil {
			log.Fatal(err)
		}
	}()
	//遍历游标获取结果数据
	for cursor.Next(context.TODO()) {
		var lr models.Poem
		//反序列化Bson到对象
		if cursor.Decode(&lr) != nil {
			fmt.Print(err)
		}
	}
	var result []models.Word
	if err = cursor.All(context.TODO(), &result); err != nil {
		log.Fatal(err)

	}
	return result
}

func SetManyWords() {
	var (
		client     = MgoCli()
		err        error
		collection *mongo.Collection
		result     *mongo.InsertManyResult
		id         primitive.ObjectID
	)
	collection = client.Database("english").Collection("word")
	result, err = collection.InsertMany(context.TODO(), []interface{}{
		models.Word{
			Id:      1,
			English: "excellent",
			Chinese: "卓越的",
			Class:   "IELTS"},
		models.Word{
			Id:      2,
			English: "unstoppable",
			Chinese: "无法阻挡的",
			Class:   "IELTS"},
		models.Word{
			Id:      1,
			English: "tremendous",
			Chinese: "极好的",
			Class:   "TOEFL"},
		models.Word{
			Id:      2,
			English: "fantastic",
			Chinese: "“奇异的",
			Class:   "TOEFL"},
	})
	if err != nil {
		log.Fatal(err)
	}
	if result == nil {
		log.Fatal("result nil")
	}
	for _, v := range result.InsertedIDs {
		id = v.(primitive.ObjectID)
		fmt.Println("自增ID", id.Hex())
	}
}
func MongoCountWord(class string) int {
	var (
		client     = MgoCli()
		collection *mongo.Collection
	)
	collection = client.Database("english").Collection("word")
	cond := models.FindByClass{Class: class}
	count, _ := collection.CountDocuments(context.TODO(), cond)
	return int(count)
}
